/*
(c) 2010 - Open Source Business Foundation e. V. (www.osbf.de)
This software is provided under Microsoft Reciprocal License (Ms-RL)
(http://www.microsoft.com/opensource/licenses.mspx#Ms-RL)
All other rights reserved
*/
// event handler
function onPageShow(event) {
  if (event.originalTarget instanceof HTMLDocument) {
    var doc = event.originalTarget;
    if (event.originalTarget.defaultView.frameElement) {
      // Frame within a tab was loaded. doc should be the root document of
      while (doc.defaultView.frameElement) {
        doc=doc.defaultView.frameElement.ownerDocument;
      }
    }
    var microFormatNodes = findMicroFormatNodes(doc);
    var tab = getTabForDocument(doc);
    if (tab) {
      tab.__microformatsContained = microFormatNodes.length;
    }
    if (isCurrentTab(getTabForDocument(event.originalTarget))) {
      setStatusbarImageTooltip(microFormatNodes.length);
    }
  }
}

// event handler
function onTabChanged(event) {
  var tab = window.top.getBrowser().selectedTab.linkedBrowser;
  if (tab) {
    setStatusbarImageTooltip(tab.__microformatsContained);
  }
}

function setStatusbarImageTooltip(nrOfMicroFormats) {
  if (nrOfMicroFormats) {
	  $_("microformats-status-image").setAttribute("src", "chrome://microformats/skin/icons/microformatsOn.gif");
	  $_("microformats-status-image").setAttribute("tooltiptext", nrOfMicroFormats + " MicroFormats found.");
  } else {
	  $_("microformats-status-image").setAttribute("src", "chrome://microformats/skin/icons/microformatsOff.gif");
	  $_("microformats-status-image").setAttribute("tooltiptext", "No MicroFormats found.");
  }
}

function isCurrentTab(tab) {
  return (window.top.getBrowser() && (tab == window.top.getBrowser().selectedTab.linkedBrowser));
}

function getTabForDocument(doc) {
  var tabIndex = window.top.getBrowser().getBrowserIndexForDocument(doc);
  return window.top.getBrowser().getBrowserAtIndex(tabIndex);
}

function $_(id) {
  return document.getElementById(id);
}

/* 
 * handle page load, focus change (back + forward button) and tab change [select]
 */
function initBrowserEventHandling() {
  window.top.getBrowser().addEventListener("load", onPageShow, true);
  window.top.getBrowser().addEventListener("pageshow", onPageShow, true);
  window.top.getBrowser().tabContainer.addEventListener("select", onTabChanged, true);
}

/* MAIN */
initBrowserEventHandling();

var mfDialog = null;
function toggleMfDialog() {
  if ((mfDialog != null) && !mfDialog.closed) {
    mfDialog.close();
    mfDialog = null;
  } else {
    mfDialog = MicroFormatDialog.onStatusIconClick(content.document);
  }
}

